package mqigdcom.mqigd.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import mqigdcom.mqigd.R;
import mqigdcom.mqigd.utils.Utils;
import com.github.barteksc.pdfviewer.PDFView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;

/**
 * PDF文件查看的界面
 */
public class PDFViewActivity extends BaseActivity {

    private PDFView mPDFView;// PDF文件查看器
    private LinearLayout vBackLayout;//返回按钮
    private String mUrlPDF;// PDF文件链接地址
    private String mStrLoading;// 字符串“加载中”
    public final int mReqStoragePermissionCode = 22;// 请求访问存储卡的权限标识码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        setCustomStatusBarVisible(true);
        if (intent != null) {
            mUrlPDF = intent.getStringExtra("pdf_url");
        }
        mStrLoading = getString(R.string.loading);
        loadOnlinePDF();
    }

    @Override
    protected View createContentView() {
        View contentView= LayoutInflater.from(this).inflate(R.layout.pdf_view_layout,null,false);
        vBackLayout=(LinearLayout)contentView.findViewById(R.id.pdf_view_back_layout);
        mPDFView=(PDFView)contentView.findViewById(R.id.pdf_view_viewer);
        vBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        return contentView;
    }

    @Override
    protected void handleClickedErrorView() {
        loadOnlinePDF();
    }

    /**
     * 加载在线PDF文件
     */
    private void loadOnlinePDF() {
        if (checkStoragePermissions()) {
            return;
        }
        if (!TextUtils.isEmpty(mUrlPDF)) {
            setLoadErrorVisible(false);
            new LoadOnlinePDFTask(this, mUrlPDF).execute();
        } else {
            setLoadErrorVisible(true);
        }
    }

    /**
     * 检测访问存储卡的权限
     *
     * @return true 需要申请权限；false 已经获得权限
     */
    private boolean checkStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        mReqStoragePermissionCode);
                return true;
            }
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (mReqStoragePermissionCode == requestCode) {
            if (permissions.length >= 2 && grantResults.length >= 2) {
                if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permissions[0]) && grantResults[0] != PackageManager.PERMISSION_GRANTED
                        || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissions[1]) && grantResults[1] != PackageManager.PERMISSION_GRANTED) {
                    showToast(getString(R.string.storage_permission_denied_can_not_view_file), Toast.LENGTH_SHORT, Gravity.BOTTOM);
                    setLoadErrorVisible(true);
                } else {
                    loadOnlinePDF();
                }
            }
        }
    }

    /**
     * 加载在线的PDF文件的任务
     */
    private static class LoadOnlinePDFTask extends AsyncTask<String, Integer, File> {

        private WeakReference<PDFViewActivity> refer;
        private String pdfUrl;

        LoadOnlinePDFTask(PDFViewActivity activity, String pdfUrl) {
            refer = new WeakReference<>(activity);
            this.pdfUrl = pdfUrl;
        }

        /**
         * 检测软引用的Activity是否可用
         *
         * @return true 可用；false 不可用
         */
        private boolean checkReferAvailable() {
            return refer != null && refer.get() != null && !refer.get().isFinishing();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (checkReferAvailable()) {
                refer.get().setLoadingVisible(true, refer.get().mStrLoading);
            }
        }

        @Override
        protected File doInBackground(String... strings) {
            if (!TextUtils.isEmpty(pdfUrl)) {
                String savedPath = Utils.getExternalSavedPath();
                if (TextUtils.isEmpty(savedPath)) {
                    return null;
                }
                File folder = new File(savedPath);
                if (!folder.exists() && !folder.mkdirs()) {
                    return null;
                }
                File file = new File(folder, pdfUrl.substring(pdfUrl.lastIndexOf("/") + 1));
                if (file.exists()) {
                    file.delete();
                }
                try {
                    URL url = new URL(pdfUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(10000);
                    int fileTotalSize = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    if (!file.createNewFile()) {
                        return null;
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int len;
                    int loopCount = 0, downloadedSize = 0;
                    while ((len = is.read(buffer)) != -1) {
                        loopCount++;
                        downloadedSize += len;
                        fos.write(buffer, 0, len);
                        if (loopCount == 1 || loopCount % 20 == 0) {
                            publishProgress(Math.round(downloadedSize * 100.0f / fileTotalSize));
                        }
                    }
                    publishProgress(100);
                    fos.close();
                    is.close();
                    conn.disconnect();
                    return file;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (values != null && values.length >= 1 && checkReferAvailable()) {
                refer.get().setLoadingVisible(true, String.format(Locale.getDefault(),
                        "%s%d%%", refer.get().mStrLoading, values[0]));
            }
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (checkReferAvailable()) {
                refer.get().setLoadingVisible(false);
                if (file != null) {
                    refer.get().mPDFView.fromFile(file).load();
                    refer.get().setLoadErrorVisible(false);
                } else {
                    refer.get().setLoadErrorVisible(true);
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isLoadingVisible()) {
            showToast(getString(R.string.file_loading), Toast.LENGTH_SHORT, Gravity.BOTTOM);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
